package com.jacksen.demo.view.services;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.Timer;

/**
 * Created by Admin on 2015/9/23.
 */
public class TestIntentService extends IntentService {

    private static final String TAG = TestIntentService.class.getSimpleName();

    private Timer timer = new Timer();

    private MyHandler handler = new MyHandler();


    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public TestIntentService(String name) {
        super(name);
        Log.d(TAG, "有参" + this);
    }

    public TestIntentService(){
        super(TAG);
        Log.d(TAG, "无参" + this);
    }

    public interface ServiceAction {
        String ACTION_START_BEAT = "ACTION_START_BEAT";
        String ACTION_STOP_BEAT = "ACTION_STOP_BEAT";
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        switch (intent.getAction()) {
            case ServiceAction.ACTION_START_BEAT:
                /*timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        Log.d(TAG, ServiceAction.ACTION_START_BEAT);
                    }
                }, 0, 10000);*/
                handler.sendMessageDelayed(handler.obtainMessage(1, null), 1000 * 10);
                break;
            case ServiceAction.ACTION_STOP_BEAT:
                /*timer.cancel();*/
                handler.removeMessages(1);
                break;
            default:
                break;
        }
    }

    /**
     *
     */
    private static class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Log.d(TAG, ServiceAction.ACTION_START_BEAT);
                    sendMessageDelayed(obtainMessage(1, null), 1000 * 10);
                    break;
                default:
                    break;
            }
        }
    }

}
